package com.oriole.admin.controller;

import com.oriole.admin.feign.ISysConfigService;
import com.oriole.admin.feign.ISysDeptService;
import com.oriole.admin.feign.ISysRoleService;
import com.oriole.admin.feign.ISysUserService;
import com.oriole.admin.utils.SecurityUtils;
import com.oriole.common.annotation.OperationLog;
import com.oriole.common.constant.ResultKey;
import com.oriole.common.constant.ResultModel;
import com.oriole.common.controller.OriolePage;
import com.oriole.common.controller.PageableUtil;
import com.oriole.common.enums.BusinessType;
import com.oriole.common.util.OrioleStringUtils;
import com.oriole.common.util.PasswordEncoderUtil;
import com.oriole.entity.sys.SysConfig;
import com.oriole.entity.sys.SysDept;
import com.oriole.entity.sys.SysRole;
import com.oriole.entity.sys.SysUser;
import com.oriole.entity.vo.SysUserPasswordVo;
import com.oriole.entity.vo.SysUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelifeke
 * Email: hautxxxyzjk@163.com
 * DateTime: 2019/4/11 12:53
 * Description:
 */
@Api(tags = {"系统用户Controller"})
@Controller
@RequestMapping("/sysUser")
public class SysUserController {

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysConfigService sysConfigService;

    @Resource
    private ISysDeptService sysDeptService;

    @Resource
    private ISysRoleService sysRoleService;

    @OperationLog(title = "系统用户-新增页面", businessType = BusinessType.TO_PAGE)
    @ApiOperation(value = "系统用户-新增页面")
    @GetMapping("/toSave")
    public ModelAndView toSave() {
        ModelAndView modelAndView = new ModelAndView("/sysUser/toSave");
        List<SysDept> sysDepts = sysDeptService.findAll().getData();
        modelAndView.addObject("sysDepts", sysDepts);
        return modelAndView;
    }

    @OperationLog(title = "系统用户-保存", businessType = BusinessType.INSERT)
    @ApiOperation(value = "系统用户-保存")
    @ResponseBody
    @PostMapping("/save")
    @Secured("ROLE_SUPER")
    public ResultModel<SysUser> save(@Valid @RequestBody SysUser sysUser) {
        SysConfig sysConfig = sysConfigService.findByConfigKey("sys_init_password").getData();
        if (null != sysConfig && OrioleStringUtils.isNotNull(sysConfig.getId())) {
            sysUser.setPassword(sysConfig.getValue());
        } else {
            sysUser.setPassword("123456");
        }
        return sysUserService.save(sysUser);
    }

    @OperationLog(title = "系统用户-编辑页面", businessType = BusinessType.TO_PAGE)
    @ApiOperation(value = "系统用户-编辑页面")
    @GetMapping("/toUpdate/{id}")
    public ModelAndView toUpdate(@PathVariable Long id) {
        ModelAndView modelAndView = new ModelAndView("/sysUser/toUpdate");
        List<SysDept> sysDepts = sysDeptService.findAll().getData();
        modelAndView.addObject("sysDepts", sysDepts);
        SysUser sysUser = sysUserService.findById(id).getData();
        modelAndView.addObject("sysUser", sysUser);
        return modelAndView;
    }

    @OperationLog(title = "系统用户-编辑", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "系统用户-编辑")
    @ResponseBody
    @PutMapping("/update")
    public ResultModel<SysUser> update(@Valid @RequestBody SysUser sysUser) {
        return sysUserService.update(sysUser);
    }

    @OperationLog(title = "系统用户-修改用户基本信息", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "系统用户-修改用户基本信息")
    @ResponseBody
    @PutMapping("/updateProfile")
    public ResultModel<SysUser> updateProfile(@Valid @RequestBody SysUser sysUser) {
        return sysUserService.updateProfile(sysUser);
    }

    @OperationLog(title = "系统用户-删除用户", businessType = BusinessType.DELETE)
    @ApiOperation(value = "系统用户-删除用户")
    @ResponseBody
    @DeleteMapping("/delete/{id}")
    @Secured("ROLE_SUPER")
    public ResultModel<Object> delete(@PathVariable("id") Long id) {
        return sysUserService.deleteById(id);
    }

    @OperationLog(title = "系统用户-批量删除用户", businessType = BusinessType.DELETE)
    @ApiOperation(value = "系统用户-批量删除用户")
    @ResponseBody
    @DeleteMapping("/deleteBatchByIds")
    @Secured("ROLE_SUPER")
    public ResultModel<Object> deleteBatchByIds(@RequestParam("ids") String ids) {
        ArrayList<Long> longs = new ArrayList<>();
        for (String id : ids.split(",")) {
            longs.add(Long.parseLong(id));
        }
        return sysUserService.deleteBatchByIds(longs);
    }

    @OperationLog(title = "系统用户-查看页面", businessType = BusinessType.TO_PAGE)
    @ApiOperation(value = "系统用户-查看页面")
    @GetMapping("/toDetail/{id}")
    public ModelAndView toDetail(@PathVariable Long id) {
        ModelAndView modelAndView = new ModelAndView("/sysUser/toDetail");
        SysUser sysUser = sysUserService.findById(id).getData();
        modelAndView.addObject("sysUser", sysUser);
        return modelAndView;
    }

    @OperationLog(title = "系统用户-根据ID查询用户", businessType = BusinessType.SELECT)
    @ApiOperation(value = "系统用户-根据ID查询用户")
    @ResponseBody
    @GetMapping("/find/{id}")
    @Secured("ROLE_SUPER")
    public ResultModel<SysUser> findById(@PathVariable("id") Long id) {
        return sysUserService.findById(id);
    }

    @OperationLog(title = "系统用户-获取系统用户列表", businessType = BusinessType.SELECT)
    @ApiOperation(value = "系统用户-获取系统用户列表")
    @ResponseBody
    @GetMapping("/findAll")
    @Secured("ROLE_SUPER")
    public ResultModel<List<SysUser>> findAll() {
        return sysUserService.findAll();
    }

    @OperationLog(title = "系统用户-用户列表页面", businessType = BusinessType.TO_PAGE)
    @ApiOperation(value = "系统用户-用户列表页面")
    @GetMapping("/index")
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView("sysUser/index");

        return modelAndView;
    }

    @OperationLog(title = "系统用户-获取系统用户列表分页", businessType = BusinessType.SELECT)
    @ApiOperation(value = "系统用户-获取系统用户列表分页")
    @ResponseBody
    @GetMapping("/findPage")
    @Secured("ROLE_SUPER")
    public ResultModel<Object> findPage(OriolePage oriolePage) {
        ResultModel<Object> resultModel = sysUserService.findPage(oriolePage);
        return ResultModel.success(PageableUtil.setResultPage(resultModel));
    }

    @OperationLog(title = "系统用户-用户基本信息页面", businessType = BusinessType.TO_PAGE)
    @ApiOperation(value = "系统用户-用户基本信息页面")
    @GetMapping("/findSysUserVo/{id}")
    public ModelAndView findSysUserVoById(@PathVariable("id") Long id) {
        ModelAndView modelAndView = new ModelAndView("/sysUser/profile");
        SysUserVo sysUserVo = sysUserService.findSysUserVoById(id).getData();
        modelAndView.addObject("sysUserVo", sysUserVo);
        return modelAndView;
    }

    @OperationLog(title = "系统用户-修改密码页面", businessType = BusinessType.TO_PAGE)
    @ApiOperation(value = "系统用户-修改密码页面")
    @GetMapping("/changePassword")
    public ModelAndView changePassword() {
        ModelAndView modelAndView = new ModelAndView("/sysUser/changePassword");
        return modelAndView;
    }

    @OperationLog(title = "系统用户-用户修改密码", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "系统用户-用户修改密码")
    @ResponseBody
    @PutMapping("/updatePassword")
    public ResultModel<SysUserVo> updatePassword(SysUserPasswordVo sysUserPasswordVo) {
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = sysUserService.findById(userId).getData();
        if (StringUtils.isBlank(sysUser.getId().toString())) {
            return ResultModel.fail(ResultKey.USER_DOES_NOT_EXIST);
        }
        String oldPassword = sysUserPasswordVo.getOldPassword();
        if (!PasswordEncoderUtil.matchesByBCrypt(oldPassword, sysUser.getPassword())) {
            return ResultModel.fail(ResultKey.PASSWORD_MISMATCH);
        }
        String password = sysUserPasswordVo.getPassword();
        if (oldPassword.equals(sysUserPasswordVo.getPassword())) {
            return ResultModel.fail(ResultKey.NEW_OLD_PASSWORD_NOT_SAME);
        }
        sysUser.setPassword(password);
        SysUser resultSysUser = sysUserService.update(sysUser).getData();
        if (null == resultSysUser || StringUtils.isBlank(resultSysUser.getId().toString())) {
            return ResultModel.fail(new SysUserVo());
        }
        SysUserVo sysUserVo = new SysUserVo();
        BeanUtils.copyProperties(resultSysUser, sysUserVo);
        return ResultModel.success(sysUserVo);
    }

    @OperationLog(title = "系统用户-设置角色页面", businessType = BusinessType.TO_PAGE)
    @ApiOperation(value = "系统用户-设置角色页面")
    @GetMapping("/toSetSysRole/{id}")
    public ModelAndView toSetSysMenu(@PathVariable Long id) {
        ModelAndView modelAndView = new ModelAndView("/sysUser/toSetSysRole");
        modelAndView.addObject("sysUserId", id);
        List<Long> checkedIds = sysRoleService.findBySysUserId(id).getData()
                .stream().map(SysRole::getId).collect(Collectors.toList());
        modelAndView.addObject("checkedIds", checkedIds);
        return modelAndView;
    }

    @OperationLog(title = "系统用户-设置角色", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "系统用户-设置角色")
    @ResponseBody
    @PutMapping("/setSysRole")
    public ResultModel<SysUser> setSysRole(@RequestParam String sysRoleIds,
                                           @RequestParam Long sysUserId) {
        return sysUserService.setSysRole(sysRoleIds, sysUserId);
    }

}
